<script setup lang="ts">
import type { FieldRule, FormInstance } from '@arco-design/web-vue'

import { updateAdminPasswordApi } from '@/apis/modules/admin'
import { useAppStore } from '@/stores/app'
import { Message } from '@arco-design/web-vue'

function passwordValidate(value: any, callback: (error?: string) => void) {
  const reg = /^[\w()`!@#$%^&*\-+=|{}[\]:;'<>,.?]{6,64}$/
  if (!value) {
    callback('密码不能为空')
  }
  if (!reg.test(value)) {
    callback('请输入6-64个字符，可包含英文字母、数字和标点符号（除空格）')
  }
}

const visible = defineModel({ default: false })
const loading = defineModel<boolean>('loading', { default: false })

const formRef = ref<FormInstance>()

const formData = reactive<any>({
  password: '',
  new_password: '',
  repeat_new_password: '',
})

const rules = computed<Record<string, FieldRule[]>>(() => {
  const res: Record<string, FieldRule[]> = {
    password: [
      {
        required: true,
        validator: passwordValidate,
      },
    ],
    new_password: [
      {
        required: true,
        message: '密码不能为空',
      },
      {
        validator(value: string, callback: (error?: string) => void) {
          if (value === formData.password) {
            return callback('新密码不能与原密码相同')
          }
        },
      },
      {
        validator: passwordValidate,
      },
    ],
    repeat_new_password: [
      {
        required: true,
        validator(value: string, callback: (error?: string) => void) {
          if (!value) {
            return callback('请再次输入新密码')
          }

          if (value !== formData.new_password) {
            return callback('两次密码输入不一致')
          }
          return callback()
        },
      },
    ],
  }
  return res
})

function handleNewPwdBlur() {
  if (formData.repeat_new_password) {
    formRef.value?.validateField('repeat_new_password')
  }
}

const appStore = useAppStore()
async function handleOk() {
  const res = await formRef.value?.validate?.()
  if (!res) {
    try {
      await updateAdminPasswordApi(formData)
      Message.success('修改成功')
      appStore.clearLoginInfoAction()
      return true
    } catch (error: any) {
      formRef.value?.setFields({
        password: {
          message: error.message,
          status: 'error',
        },
      })
      return false
    }
  } else {
    return false
  }
}

async function handleOpen() {
  formData.password = ''
  formData.new_password = ''
  formData.repeat_new_password = ''
}
</script>

<template>
  <resource-dialog
    v-model:visible="visible"
    :width="480"
    :mask-closable="false"
    title="修改密码"
    :loading="loading"
    :before-ok="handleOk"
    :before-open="handleOpen"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      layout="vertical"
    >
      <a-form-item
        field="password"
        label="原密码"
        validate-trigger="blur"
        asterisk-position="end"
        hide-asterisk
      >
        <a-input-password
          v-model="formData.password"
          placeholder="请输入原密码"
          :input-attrs="{ autocomplete: 'off' }"
        />
      </a-form-item>
      <a-form-item
        field="new_password"
        label="新密码"
        validate-trigger="blur"
        asterisk-position="end"
        class="new_password-form-item"
        hide-asterisk
      >
        <!-- <div>
          <span class="inline-block pb-2 text-5 text-xs">请输入6-64个字符，可包含英文字母、数字和标点符号(除空格外)</span>
          <a-input-password
            v-model="formData.new_password"
            placeholder="请输入新密码"
            @blur="handleNewPwdBlur"
          />
        </div> -->
        <a-input-password
          v-model="formData.new_password"
          placeholder="请输入新密码"
          @blur="handleNewPwdBlur"
        />
      </a-form-item>
      <a-form-item
        field="repeat_new_password"
        label="确认新密码"
        validate-trigger="blur"
        asterisk-position="end"
        class="mb-0!"
        hide-asterisk
      >
        <a-input-password
          v-model="formData.repeat_new_password"
          placeholder="请再次输入新密码"
          :input-attrs="{ autocomplete: 'off' }"
        />
      </a-form-item>
    </a-form>
  </resource-dialog>
</template>

<style lang="less" scoped></style>
